package com.tanhua.manage.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.manage.domain.UserFrezze;
import com.tanhua.manage.utils.FreezerTimeTypeUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;
import javax.xml.ws.Response;
import java.util.*;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VideoApi videoApi ;


    @Reference
    private PublishApi publishApi;

    @Reference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 查询所有的探花客户端账号信息
     * @param pageNum
     * @param pagesize
     * @return
     */
    public ResponseEntity<Object> findByPage(Integer pageNum, Integer pagesize) {
       Page page = userInfoApi.findByPage(pageNum,pagesize);
       PageResult pageResult  = new PageResult(pageNum,pagesize,(int)page.getTotal(),page.getRecords());
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 根据id号查找用户逇信息
     * @param userId
     * @return
     */
    public ResponseEntity<Object> findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 根据用户的id查找当前用户发布的小视频
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    public ResponseEntity<Object> findVideosList(Integer page, Integer pagesize, Long uid) {
        //1. 找到用户发布的小视频
       PageResult pageResult =  videoApi.findByPage(page,pagesize,uid);
        //2. 得到分页Items List<Video>
        List<Video> videoList = (List<Video>) pageResult.getItems();

        //3. 创建VoList，里面存储VideoVo
        List<VideoVo> voList = new ArrayList<>();

        //4.把Video转换为VideoVo
        if(videoList!=null){
            for (Video video : videoList) {
                VideoVo vo = new VideoVo();
                UserInfo userInfo = userInfoApi.findById(video.getUserId());
                if(userInfo!=null){
                    BeanUtils.copyProperties(userInfo,vo);
                }
                BeanUtils.copyProperties(video,vo);
                vo.setId(video.getId().toString());
                vo.setCover(video.getPicUrl()); //视频的封面
                vo.setSignature(video.getText());
                voList.add(vo);
            }
        }
        pageResult.setItems(voList);
        //5. 返回响应
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 作用： 查询用户个人的动态
     * @param page
     * @param pagesize
     * @param uid
     * @param state
     * @return
     */

    public ResponseEntity<Object> findMovementsList(Integer page, Integer pagesize, Long uid, String state) {
        //1. 查询用户自己的动态，得到分页对象
        PageResult pageResult = publishApi.findPublishList(page, pagesize, uid, state);
        if (Objects.nonNull(uid)) {
            setMovementsVo(pageResult);
        }
        return ResponseEntity.ok(pageResult);

    }


    /**
     * 好友动态及推荐动态公共方法
     */
    public void setMovementsVo(PageResult pageResult) {

        // 获取当前页的数据
        List<Publish> publishList = (List<Publish>) pageResult.getItems();

        // 3.封装返回结果
        List<MovementsVo> voList = new ArrayList<>();

        if (publishList != null) {
            for (Publish publish : publishList) {
                // 3.1 创建vo对象
                MovementsVo vo = new MovementsVo();
                // 3.2 查询用户详情信息
                UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                // 3.3 封装用户信息
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                    if (userInfo.getTags() != null) {
                        vo.setTags(userInfo.getTags().split(","));
                    }
                }
                // 3.4 封装动态信息
                BeanUtils.copyProperties(publish, vo);
                if (publish.getMedias() != null) {
                    vo.setImageContent(publish.getMedias().toArray(new String[]{}));
                }

                // 3.5 封装其他参数
                vo.setDistance("50米");
                vo.setCreateDate(DateUtil.format(new Date(publish.getCreated()),"yyyy-MM-dd HH:mm:ss")); // 转换时间（1小时之前）
                vo.setId(publish.getId().toString());
                vo.setHasLiked(0);
                vo.setHasLoved(0);

                // 3.6 添加vo对象
                voList.add(vo);
            }
        }
        pageResult.setItems(voList);
    }

    //查询动态详情
    public ResponseEntity<Object> findMovementsById(String publishId) {
        //1.查找到动态
        Publish publish = publishApi.findById(publishId);
        //2 把publish转换为moveMentVo
        // 3.1 创建vo对象
        MovementsVo vo = new MovementsVo();
        // 3.2 查询用户详情信息
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        // 3.3 封装用户信息
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        // 3.4 封装动态信息
        BeanUtils.copyProperties(publish, vo);
        if (publish.getMedias() != null) {
            vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        }
        // 3.5 封装其他参数
        vo.setDistance("50米");
        vo.setCreateDate(DateUtil.format(new Date(publish.getCreated()),"yyyy-MM-dd HH:mm:ss")); // 转换时间（1小时之前）
        vo.setId(publish.getId().toString());
        vo.setHasLiked(0);
        vo.setHasLoved(0);
        return ResponseEntity.ok(vo);
    }

    /**
     * 查询评论列表
     * @param publishId
     * @param page
     * @param pagesize
     * @return
     */
    public ResponseEntity<Object> findCommentsById(String publishId, Integer page, Integer pagesize) {
        //1. 查找该动态的评论列表
        PageResult pageResult =commentApi.queryCommentsList(publishId,page,pagesize);
        //2. 得到pageResult的items
        List<Comment> commentList = (List<Comment>) pageResult.getItems();
        //3. 创建voList
        List<CommentVo> voList = new ArrayList<>();
        //4. 把CommentList转移到volist
        if(commentList!=null){
            for (Comment comment : commentList) {
                CommentVo vo = new CommentVo();
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                if(userInfo!=null) {
                    vo.setAvatar(userInfo.getAvatar());
                    vo.setNickname(userInfo.getNickname());
                }
                vo.setId(comment.getId().toString());
                vo.setContent(comment.getContent());
                vo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy年MM月dd日 HH:mm:ss"));
                vo.setLikeCount(comment.getLikeCount());
                vo.setHasLiked(0);
                voList.add(vo);
            }
        }
        //5. pageresult重新设置items，把voList设置到页面对象
        pageResult.setItems(voList);
        //6. 返回响应
        return ResponseEntity.ok(pageResult);
    }



    //返回message封装的数据？
    public ResponseEntity<Object> pass(List<String> publishId) {
        Long upset = publishApi.pass(publishId);
        HashMap<String, String> result = new HashMap<>();
        if (upset > 0) {
            result.put("message", "操作成功");
        }
        result.put("message", "操作失败");
        return ResponseEntity.ok(result);
    }


    //拒绝通过
    public ResponseEntity<Object> reject(List<String> publishId) {
        Long upset = publishApi.reject(publishId);
        HashMap<String, String> result = new HashMap<>();
        if (upset > 0) {
            result.put("message", "操作成功");
        }
        result.put("message", "操作失败");
        return ResponseEntity.ok(result);
    }


    /**
     * 接口名称：用户解冻操作
     * 接口路径：POST/manage/users/unfreeze
     */
    public ResponseEntity<Object> UserUnfreeze(String userId, String reasonsForThawing) {
        //查找到用户的信息
        UserInfo userInfo = userInfoApi.findById(Long.valueOf(userId));
        //更新用户的状态
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);
        //删除Redis的记录
        redisTemplate.delete(1+"_USERSTATUS_"+userId);
        redisTemplate.delete(2+"_USERSTATUS_"+userId);
        redisTemplate.delete(3+"_USERSTATUS_"+userId);
        return ResponseEntity.ok("");
    }


    /**
     * 接口名称：用户冻结操作
     * 接口路径：POST/manage/users/freeze
     */
    public ResponseEntity<Object> UserFreeze(UserFrezze userFrezze) {
        //查找到用户的信息
        UserInfo userInfo = userInfoApi.findById(Long.valueOf(userFrezze.getUserId()));
        //更新用户的状态
        userInfo.setUserStatus("2");
        userInfoApi.update(userInfo);
        //Redis中存储，key=冻结的类型_USERSTATUS_冻结用户的ID，value=UserFrezze类
        String jsonString = JSON.toJSONString(userFrezze);
        //冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
        redisTemplate.opsForValue().set(userFrezze.getFreezingRange()+"_USERSTATUS_"+userFrezze.getUserId(),
                jsonString, FreezerTimeTypeUtils.getTime(userFrezze.getFreezingTime()));
        return ResponseEntity.ok("");

    }
}
